<template>
  <!-- 新增/修改 -->
  <el-dialog
    v-model="dialogVisible"
    title="用户角色分配"
    @closed="closedDialog"
    width="80%"
    :close-on-click-modal="false"
  >
    <el-row :gutter="15">
      <el-col :span="10">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>菜单树</span>
            </div>
          </template>
          <div>
            <el-tree
              :data="menusTree"
              ref="menusTreeRef"
              node-key="id"
              @node-click="checkboxMenuTree"
              show-checkbox
              :props="defaultProps"
              v-loading="treeLoading"
            />
          </div>
        </el-card>
      </el-col>
      <el-col :span="14">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>菜单按钮列表</span>
            </div>
          </template>
          <div>
            <el-table
              :data="buttonList"
              ref="buttonTableRef"
              border
              style="width: 100%"
              @select="authMenuBtnSubmit"
              v-loading="tableLoading"
            >
              <el-table-column
                type="selection"
                prop="id"
                align="center"
                width="55"
              />
              <el-table-column
                prop="buttonTitle"
                align="center"
                label="按钮标题"
              />
              <el-table-column
                prop="buttonCode"
                align="center"
                label="按钮编码"
              />
              <el-table-column prop="method" align="center" label="请求方式" />
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <template #footer>
      <el-button @click="closedDialog">取消</el-button>
      <el-button
        type="primary"
        @click="authorizeMenusSubmit()"
        :loading="loading"
      >
        确认
      </el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, onBeforeMount } from "vue";
import MenuButtonAPI, { type MenuButtonVO } from "@/api/system/sys/menuButton";
import RoleAuthorizationAPI from "@/api/system/sys/roleAuth";
import { MENU_RESOURCE_TYPE } from "@/enums/GlobalConst";
import MenuAPI, { type MenuVO } from "@/api/system/sys/menu";
import { type ElTree, type ElTable, ElNotification } from "element-plus";

/**
 * 角色配置权限
 */
defineOptions({
  name: "AuthorizeRoleDialog",
});
const props = defineProps({
  /** 角色code */
  roleCode: {
    type: String,
    required: true,
  },
  closedDialog: {
    type: Function,
    required: true,
  },
});

/** 菜单树 */
const menusTree = ref<MenuVO[]>([]);
/** 菜单按钮树 */
const buttonList = ref<MenuButtonVO[]>([]);
const menusTreeRef = ref<InstanceType<typeof ElTree>>();
const buttonTableRef = ref<InstanceType<typeof ElTable>>();
const dialogVisible = ref<boolean>(true);
const treeLoading = ref<boolean>(false);
const loading = ref<boolean>(false);
const tableLoading = ref<boolean>(false);
/** 角色权限表单 */
const roleAuthForm = ref<any>({
  resourceIds: [],
  /** 0菜单|1按钮 */
  resourceType: undefined,
  menuCode: undefined,
});
const defaultProps = {
  children: "children",
  label: "menuTitle",
};

/** 关闭弹窗 */
const closedDialog = () => {
  props.closedDialog(false);
};

/** 获取菜单按钮列表 */
const checkboxMenuTree = (data: any) => {
  tableLoading.value = true;
  MenuButtonAPI.getSysMenuButtonListApi({ menuId: data.id }).then((res) => {
    if (res && res.status === 200) {
      buttonList.value = res.data.rows;
      getButAuthByRoleCode();
    }
  });
};

/** 获取角色菜单的按钮列表 */
const getButAuthByRoleCode = () => {
  RoleAuthorizationAPI.getAuthByRoleCodeApi(props.roleCode, MENU_RESOURCE_TYPE.button)
    .then((res) => {
      if (res && res.status === 200) {
        // 获取按钮权限对应的按钮列表
        const buttons = getButAuthByButId(res.data);
        if (buttons) {
          // 设置按钮列表的权限选中效果
          buttons.forEach((row: any) => {
            buttonTableRef.value?.toggleRowSelection(row, true);
          });
        } else {
          // 没有授权的按钮，则清空列表多选框选择效果
          buttonTableRef.value?.clearSelection();
        }
      }
    })
    .finally(() => {
      tableLoading.value = false;
    });
};

/**获取按钮权限对应的按钮列表 */
const getButAuthByButId = (butIds: any) => {
  if (butIds) {
    const buttons: any[] = [];
    // 后台获取的按钮ids和当前页面按钮列表匹配，成功则返回数据
    butIds.forEach((butId: any) => {
      for (const but of buttonList.value) {
        if (parseInt(butId) === but.id) {
          buttons.push(but);
          break;
        }
      }
    });
    return buttons;
  } else {
    return undefined;
  }
};

/** 授权菜单确认 */
const authorizeMenusSubmit = () => {
  // 获取选中的子集菜单keys数组
  roleAuthForm.value.resourceIds = menusTreeRef.value!.getCheckedKeys();
  // 获取半选中的菜单keys数组
  const keys: any = menusTreeRef.value!.getHalfCheckedKeys();
  roleAuthForm.value.resourceIds.push(...keys);
  // 设置授权资源类型：菜单
  roleAuthForm.value.resourceType = MENU_RESOURCE_TYPE.menu;
  RoleAuthorizationAPI.setRoleAuthApi(props.roleCode, roleAuthForm.value).then((res) => {
    if (res && res.status === 200) {
      ElMessage.success("菜单授权成功");
      props.closedDialog();
    }
  });
};

/**授权菜单按钮 */
const authMenuBtnSubmit = (selection: any) => {
  roleAuthForm.value.resourceIds = [];
  for (const row of selection) {
    roleAuthForm.value.resourceIds.push(row.id);
  }
  roleAuthForm.value.resourceType = MENU_RESOURCE_TYPE.button;
  RoleAuthorizationAPI.setRoleAuthApi(props.roleCode, roleAuthForm.value).then((res) => {
    if (res && res.status === 200) {
      ElNotification({
        title: "按钮授权",
        message: "授权成功",
        type: "success",
      });
    }
  });
};

/** 页面渲染完成后初始化 */
onBeforeMount(async () => {
  treeLoading.value = true;
  if (props.roleCode) {
    // 获取系统菜单
    await MenuAPI.getMenuTreesApi().then((res) => {
      if (res && res.status === 200) {
        menusTree.value = res.data;
      }
    });
    // 获取角色有权限菜单树
    await RoleAuthorizationAPI.getMenuAuthByRoleCodeApi(props.roleCode)
      .then((res) => {
        if (res && res.status === 200) {
          menusTreeRef.value!.setCheckedKeys(res.data);
        }
      })
      .finally(() => {
        treeLoading.value = false;
      });
  }
});
</script>

<style lang="scss" scoped></style>
